package com.ym.b2b.order.tk.impl;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ym.b2b.commons.exception.BaseException;
import com.ym.b2b.order.dao.EmSOrderConfirmItemDao;
import com.ym.b2b.order.sqlbean.EmSOrderConfirmItem;
import com.ym.b2b.order.tk.TKDBFactroy;
import com.ym.b2b.order.tk.TkService;
import com.ym.b2b.order.vo.OrderInfoVO;
import com.zc.commons.base.Result;
import com.zc.commons.service.ZcService;

@Service
public class TkServiceImpl extends ZcService implements TkService {

    @Autowired
    private EmSOrderConfirmItemDao emSOrderItemDao;

    @Override
    public Result dealOrder(OrderInfoVO vo) throws BaseException {
        Result ret = new Result();
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            conn = TKDBFactroy.getTkCon();
            conn.setAutoCommit(false);
            stmt = conn.createStatement();

        } catch (Exception e) {

            throw new BaseException(e.getMessage());
        }
        try {
            // STEP 1 插入零时表
            /**
             * --djbh 单据编号 / --rq 日期 --dwbh 单位内码 单位表的主键 --ywy 业务员 --hsje 含税金额 --spid 商品内码 商品表的主键 --dw 药品包装单位 --baozhshl
             * 药品的包装数量(通常说的多少件) --lingsshl 零散数量 --shl 数量 --dj 单价 --hshj 含税价 --je 金额 --hsje 含税金额 --she 税额 --is_zx
             * 是否执行(提取之前值为否，提取后为是)
             **/
            logger.info("金额测试：" + vo.getConfirmMoney());
            String insertWebddhz = "insert into webddhz(djbh,rq,dwbh,ywy,hsje,je,she,zt,is_kfp)values('" + vo.getOrderCode()
                                   + "',getdate(),'" + vo.getUser().getBuyerCode() + "','" + vo.getSalesman() + "',0 ,"
                                   + vo.getConfirmMoney() + ",0,'200','"+(vo.getIsInvoice()==1?"是":"否")+"')";

            logger.info("插入接口表总单：" + insertWebddhz);
            stmt.executeUpdate(insertWebddhz);
            // 保存明细

            SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");
            int i = 1;
            for (EmSOrderConfirmItem confirmItem : vo.getEmSOrderConfirmItemList()) {
                String insertItemSql = "insert into webddmx(djbh,spid,shl,dj,is_zx,je,code,pihao,baozhiqi)values";
                String endSql = "('" + vo.getOrderCode() + "','" + confirmItem.getProductCode() + "',"
                                + confirmItem.getConfirmAmount() + "," + confirmItem.getSalePrice() + ",'否',"
                                + confirmItem.getConfirmAmount() * confirmItem.getSalePrice() + ",'200','"+confirmItem.getBatchNumber()+"','"+(confirmItem.getValidDate()==null?"":sdf.format(confirmItem.getValidDate()))+"')";

                logger.info("保存接口表明细：" + insertItemSql + endSql);
                stmt.executeUpdate(insertItemSql + endSql);
                i++;
            }

            // STEP 2 调用存过
            CallableStatement query = conn.prepareCall("{call web_kcjy(?,?,?)}");
            query.setString(1, vo.getOrderCode());
            query.registerOutParameter(2, java.sql.Types.INTEGER);
            query.registerOutParameter(3, java.sql.Types.VARCHAR);
            query.execute();

            String querySql = "select * from webddmx where djbh='" + vo.getOrderCode() + "'";
            rs = stmt.executeQuery(querySql);

            while (rs.next()) {
                // update 我的
                logger.info("is_zx:" + rs.getString("is_zx") + "code:" + rs.getString("code"));
                if (rs.getString("code").equals("100")) {
                    ret.setCodeResult(Result.CODE_100, ret.getResult() + rs.getString("spid") + "库存不足!");
                }
            }
            conn.setAutoCommit(true);
            conn.commit();
            return ret;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
                throw new BaseException("本地系统事务回滚异常!");
            }
            throw new BaseException("保存到ERP系统 订单失败!" + e.getMessage());
        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
                if (rs != null) {
                    rs.close();
                }
                if (conn != null) {
                    conn.close();
                }

            } catch (SQLException e) {
                e.printStackTrace();
                throw new BaseException("关闭本地数据库连接异常:" + e.getMessage());
            }

        }

    }

    @Override
    public Result cancelOrder(OrderInfoVO vo) throws BaseException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void updateOrder(OrderInfoVO vo, EmSOrderConfirmItem item) throws BaseException {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            conn = TKDBFactroy.getTkCon();
            conn.setAutoCommit(false);
            stmt = conn.createStatement();

        } catch (Exception e) {

            throw new BaseException(e.getMessage());
        }
        try {
            //更新订单 webddhz
            if(!StringUtils.isEmpty(vo.getOrderCode())&&vo.getConfirmMoney()!=null){
                String updateWebddhz="update webddhz set je="+vo.getConfirmMoney()+" where djbh='"+vo.getOrderCode()+"'";

                logger.info("更新订单：" + updateWebddhz);
                stmt.executeUpdate(updateWebddhz);
            }

            //删除订单 webddhz
            if(!StringUtils.isEmpty(vo.getOrderCode())&&vo.getConfirmMoney()==null){
                String deleteWebddhz="delete from webddhz where djbh='"+vo.getOrderCode()+"'";

                logger.info("删除订单：" + deleteWebddhz);
                stmt.executeUpdate(deleteWebddhz);
            }

            // 删除订单明细 webddmx
            if(!StringUtils.isEmpty(vo.getOrderCode())&&!StringUtils.isEmpty(item.getProductCode())&&!StringUtils.isEmpty(item.getBatchNumber())){
                String deleteWebddmx="delete from webddmx where djbh='"+vo.getOrderCode()+"' and spid='"+item.getProductCode()+"' and pihao='"+item.getBatchNumber()+"'";

                logger.info("删除订单明细：" + deleteWebddmx);
                stmt.executeUpdate(deleteWebddmx);
            }

            conn.setAutoCommit(true);
            conn.commit();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
                throw new BaseException("本地系统事务回滚异常!");
            }
            throw new BaseException("ERP系统 删除订单失败!" + e.getMessage());
        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
                if (rs != null) {
                    rs.close();
                }
                if (conn != null) {
                    conn.close();
                }

            } catch (SQLException e) {
                e.printStackTrace();
                throw new BaseException("关闭本地数据库连接异常:" + e.getMessage());
            }
        }
    }
}
